<template>

  <div class="mixin-components-container">

    <el-card class="box-card">
      <el-row>
        <div style="margin-bottom:50px;">
          <el-col :xs="8" :sm="6" :md="4" :lg="2" class="text-center">
            <el-button icon="fa fa-plus-square-o fa-lg" class="btn0" @click="createHandle">
              &nbsp;&nbsp;新增
            </el-button>
          </el-col>
          <el-col :xs="8" :sm="6" :md="4" :lg="2" class="text-center">
            <el-button icon="fa fa-trash-o fa-lg" class="btn0" @click="handleDeleteAll">&nbsp;&nbsp;删除</el-button>
          </el-col>
          <el-col :xs="8" :sm="6" :md="4" :lg="4" class="text-center">
            <el-select v-model="listQuery.modid" placeholder="选择模块" :remote-method="getRemoteModelList" filterable default-first-option remote>
              <el-option
                v-for="item in mlist"
                :key="item.id"
                :label="item.modname"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="4" :xs="8" :sm="6" :md="4" :lg="4" class="text-center">
            <el-select v-model="listQuery.statflg" placeholder="状态" filterable default-first-option>
              <el-option
                v-for="item in statlist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="4" :xs="8" :sm="6" :md="4" :lg="4" class="text-center">
            <el-select v-model="listQuery.mobsyn" placeholder="同步移动端" filterable default-first-option>
              <el-option
                v-for="item in synlist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="8" :xs="8" :sm="6" :md="4" :lg="8" class="text-center">
            <el-row>
              <el-col :span="16">
                <el-input
                  v-model="listQuery.title"
                  placeholder="请输入标题"
                  name="title"
                  type="text"
                  tabindex="1"
                  autocomplete="off"
                />

              </el-col>
              <el-col :span="2" :xs="8" :sm="6" :md="4" :lg="2">
                <el-button class-name="search-icon" icon-class="search" @click="handleFilter">
                  <svg-icon class-name="search-icon" icon-class="search" />
                </el-button>
              </el-col>

            </el-row>
          </el-col>
        </div>

      </el-row>
    </el-card>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" width="30">
        <template slot="header" slot-scope="slot">
          <el-checkbox
            v-model="checkAll"
            value="true"
            :checked="checkAll"
            :class="{'dischk':disabled}"
            @change="handleChange"
          />

        </template>
        <template slot-scope="{row}" type="selection">
          <el-checkbox v-model="row.del" :value="row.id" @change="handleitemChange(row, $event)" />
        </template>

      </el-table-column>
      <el-table-column label="No" prop="id" align="center" width="50">
        <template slot-scope="{row}">
          <span>{{ row.no }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接" prop="imgsrc" align="center" width="120">
        <template slot-scope="{row}">
          <a v-waves target="_blank" :href="row.imgsrc"><span class="link">{{ row.imgsrc }}</span></a>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="imgpath" align="center" width="120">
        <template slot-scope="{row}">
          <mallki class-name="mallki-text link" :text="row.imgpath" />
        </template>
      </el-table-column>
      <el-table-column label="移动端图片" prop="mobimgpath" align="center" width="120">
        <template slot-scope="{row}">
          <mallki class-name="mallki-text link" :text="row.mobimgpath" />
        </template>
      </el-table-column>
      <el-table-column label="同步移动端" prop="mobsyn" align="center" width="80">
        <template slot-scope="{row}">
          <span> {{ row.mobsyn | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块" align="center" width="80">
        <template slot-scope="{row}">
          <span> {{ row.modname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="80">
        <template slot-scope="{row}">
          <span> {{ row.uname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间 " align="center" width="160">
        <template slot-scope="{row}">
          <span> {{ row.cdate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序 " align="center" width="80">
        <template slot-scope="{row}">
          <span> {{ row.orderby }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.statflg"
            active-value="1"
            inactive-value="0"
            class="drawer-switch"
            @change="changeswitch(row, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作 " align="center" width="80">
        <template slot-scope="{row,$index}">
          <div class="fixed-width">
            <div class="icon-item" @click="handleUpdate(row)">
              <i class="el-icon-edit" />
            </div>
            <div class="icon-item">
              <i class="el-icon-delete" @click="handleDelete(row,$index)" />
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog custom-class="customWidth" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600" @close="close">
      <el-form ref="dataForm" v-model="temp" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="图片" prop="imgpath2">
          <single-image-upload
            ref="child"
            :width="70"
            :height="100"
            url=""
            @func="getMsgFormSon1"
            @uploadsuccess="cropSuccess"
          /><div style="display:none"><el-input v-model="temp.imgpath2" type="text" /></div>
        </el-form-item>
        <el-form-item label="移动端图片">
          <el-checkbox v-model="temp.mobsyn1" @change="changync(temp)" />
        </el-form-item>
        <el-form-item label="图片" prop="mobimgpath2">
          <single-image-upload
            ref="child2"
            :width="70"
            :height="100"
            @func="getMsgFormSon2"
            @uploadsuccess="cropSuccess"
          />
        </el-form-item>
        <el-form-item label="所属模块" prop="modid">
          <el-select v-model="temp.modid" class="filter-item">
            <el-option v-for="item in mlist1" :key="item.id" :label="item.modname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接">
          <el-input v-model="temp.imgsrc" />
        </el-form-item>
        <el-form-item label="排序" prop="orderby">
          <el-input v-model="temp.orderby" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="temp.statflg"
            active-value="1"
            inactive-value="0"
            class="drawer-switch"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" :loading="btnloading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
        <el-button type="reset" @click="close">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { fetchList, updateBanner, deleteById, deleteAll, changeStatus, createBanner } from '@/api/banner'
import PanThumb from '@/components/PanThumb'
import MdInput from '@/components/MDinput'
import Mallki from '@/components/TextHoverEffect/Mallki'
import waves from '@/directive/waves/index.js' // 水波纹指令
import { getAllMlist } from '@/api/remote-method'
import SingleImageUpload from '@/components/Upload/SingleImage'
import { Message } from 'element-ui'
import { checkMax20000 } from '@/utils/validate'
const obj = {
  name: 'BannerSearch',
  components: {
    PanThumb,
    MdInput,
    Mallki,
    Pagination,
    SingleImageUpload
  },
  directives: {
    waves
  },
  computed: {

  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '是',
        0: '否',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    modename() {

    }
  },
  data() {
    const validateimgpath2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }

    return {
      btnloading: false,
      dlist: [],
      no: 1,
      disabled: true,
      checkAll: false,
      listQuery: {
        page: 1,
        limit: 10,
        sort: '+id',
        title: '',
        modid: '',
        mobsyn: '',
        statflg: ''
      },
      textMap: { update: '更新', create: '添加' },
      dialogFormVisible: false,
      dialogStatus: '',
      showReviewer: false,
      rules: {
        // image_uri: [{ validator: validateRequire }],
        // title: [{ validator: validateRequire }],
        // content: [{ validator: validateRequire }],
        // source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
        imgpath2: [{ validator: validateimgpath2, message: '图片必须输入', trigger: 'change' }],
        orderby: [{ required: true, message: '排序必须输入', trigger: 'blur' }, { validator: checkMax20000, trigger: 'change'}],
        title: [{ required: true, message: '标题必须输入', trigger: 'blur' }],
        modid: [{ required: true, message: '模块必须选择', trigger: 'change' }]
      },
      temp: {},
      tableKey: 0,
      total: 0,
      listLoading: false,
      mlist: [],
      mlist1: [],
      list: null,
      synlist: [
        { id: -1, name: '同步移动端' },
        { id: 1, name: '是' },
        { id: 0, name: '否' }
      ],
      statlist: [
        { id: -1, name: '状态' },
        { id: 1, name: '启用' },
        { id: 0, name: '禁用' }
      ],
      imagecropperShow: true,
      imagecropperKey: 0,
      currrow: {}
    }
  },
  created() {
    this.getRemoteModelList()
  },
  methods: {
    getRemoteModelList(query) {
      getAllMlist(query).then(response => {
        if (!response.data) return
        this.mlist1 = Object.assign(response.data)
        this.mlist = response.data
        // that.mlist.unshift({ id: -1, modname: '模块' })
        this.listQuery.model = -1
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    createHandle() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      deleteById(row).then(res => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      }).then(res => {
        this.list.splice(index, 1)
        this.dlist = this.dlist.filter(item => (item.id == row.id))
      })
    },
    handleDeleteAll() {
      if (this.dlist.length === 0) {
        Message({
          message: '没有选中的记录',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        this.listLoading = true
        deleteAll(this.dlist).then(res => {
          this.$notify({
            title: '成功',
            message: res.msg,
            type: 'success',
            duration: 2000
          })
        }).then(res => {
          this.list = this.list.filter(item => {
            return item.del != true
          })
          this.dlist = []
          this.listLoading = false
        })
      }

    },
    changeswitch(data, index) {
      changeStatus(data).then(res => {
        data.cdate = res.data.cdate
      })
    },
    getList() {
      this.listLoading = true
      const that = this
      this.dlist = []
      fetchList(this.listQuery).then(response => {
        that.list = response.data.list.map((item, n) => {
          // item.id = n+1;
          item.no = (that.listQuery.page - 1) * that.listQuery.limit + n + 1
          item.del = false
          item.mobsyn1 = item.mobsyn == '1'
          // item.statflgsw = item.statflg == 1
          return item
        })
        that.total = response.data.total
        if (that.total != 0) {
          that.disabled = false
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleChange(val) {
      this.dlist = []
      this.list.forEach(item => {
        item.del = val
        if (val) {
          this.dlist.push(item.id)
        }
      })
    },
    handleitemChange(row, event) {
      if (event) {
        this.dlist.push(row.id)
      } else {
        this.dlist = this.dlist.filter(item => item !== row.id)
      }

      let count = 0
      this.list.forEach(item => {
        if (item.del) {
          count++
        }
      })
      if (count === this.list.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.currrow = row
      this.temp = Object.assign({}, row)
      this.temp.data = row
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.child.tempUrl = row.imgpath2 || ''
        this.$refs.child2.tempUrl = row.mobimgpath2 || ''
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        imgpath2: '',
        mobimgpath2: '',
        modid: '',
        imgsrc: '',
        orderby: '',
        statflg: '',
        mobsyn: '0',
        mobsyn1: false,
        title: ''
      }
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.image = resData.files.avatar
    },
    close() {
      this.dialogFormVisible = false
      this.resetTemp()
      this.$nextTick(() => {
        this.$refs.child.tempUrl = ''
        this.$refs.child2.tempUrl = ''
      })
    },
    getMsgFormSon1(data) {
      if (data['img1']) {
        this.temp.imgpath2 = data['img1']
      } else {
        this.temp.imgpath2 = ''
      }
    },
    getMsgFormSon2(data) {
      if (data['img1']) {
        this.temp.mobimgpath2 = data['img1']
      } else {
        this.temp.mobimgpath2 = ''
      }
    },
    changync(row) {
      row.mobsyn = row.mobsyn1 ? 1 : 0
    },
    resetData() {
      if (this.dialogStatus === 'create') {
        this.resetTemp()
      } else {
        this.handleUpdate(this.temp.data)
      }
    },
    updateData() {
      if (!this.validateForm()) {
        return
      }
      this.btnloading = true
      const that = this
      let flg = false
      for (let prop in this.temp) {
        if (prop !== 'data' && this.temp.data[prop] !== this.temp[prop]) {
          flg = true
        }
      }
      if (!flg) {
        this.$message({
          message: '没有变更',
          type: 'warn'
        })
        return
      }
      this.mergetupdate(this.temp, this.temp.data)
      delete this.temp.data
      updateBanner(this.temp).then(response => {
        for (const pro in response.data) {
          that.currrow[pro] = response.data[pro]
          if (pro === 'modid') {
            that.mlist.forEach(item => {
              if (item.id == response.data.modid) {
                that.currrow.modname = item.modname
              }
            })
          }
          if (pro === 'mobsyn') {
            that.currrow.mobsyn1 = that.currrow[pro] == '1' ? true : false
          }
        }
        that.btnloading = false
      }).then(res => {
        this.close()
      })
    },
    createData() {
      if (!this.validateForm()) {
        return
      }
      this.btnloading = true
      const that = this
      createBanner(this.temp).then(response => {
        that.btnloading = false
      }).then(res => {
        this.close()
      })
    },
    mergetupdate(data1, data2) {
      for (const p in data1) {
        if (p !== 'id' && p !== 'cdate') {
          if (data1[p] === data2[p]) {
            delete data1[p]
          }
        }
      }
    },
    validateForm() {
      let flg = false
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          flg = true
        } else {
          this.$message({
            message: '请查看验证为必传项',
            type: 'error'
          })
          flg = false
        }
      })
      return flg
    }
  }
}
export default obj
</script>

<style>
.btn0 {
  word-letter: 10px;
}
.mixin-components-container {
  background-color: #f0f2f5;
  padding: 30px;
  min-height: calc(100vh - 84px);
}
.component-item{
  min-height: 100px;
}
.link {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: blue;
}
.dischk {
  display: none
}
.icon-item {
  height: 55px;
  text-align: center;
  width: 30px;
  font-size: 30px;
  color: #24292e;
  cursor: pointer;
  display: inline-block;
}
.icon-item:hover {
    color: #1890ff;
    border-color: #badeff;
    background-color: #e8f4ff;
}
.fixed-width {
  display: flex;
  justify-content: space-around
}
.el-dialog.customWidth {
  width: 70% !important
}
</style>
